//
//  CommunityDetailViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/24.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "CommunityDetailViewController.h"
#import "HotPostTableViewCell.h"
#import "CommentViewController.h"
#import "CommunityList.h"
#import "MBProgressHUD.h"
@interface CommunityDetailViewController ()

@property(nonatomic,retain)NSMutableArray *hotPostArray;

@end

@implementation CommunityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.hotPostArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
    self.update=YES;
    [self.tableView registerNib:[UINib nibWithNibName:@"HotPostTableViewCell" bundle:nil] forCellReuseIdentifier:@"hotPostCell"];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    if (self.update) {
        [self loadNewData];
    }
    self.update = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}







#pragma mark- 下拉刷新（请求数据，结束header） -
-(void)loadNewData{
    //    出现大菊花
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//http://api.gongniucaijing.com/Weiba/listpost ? weiba_id=3&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&number=15
    NSString *urlStr = @"http://api.gongniucaijing.com/Weiba/listpost";
    [self.hotPostArray removeAllObjects];
    [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
        
        NSDictionary *dic = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                              @"number":@"15",
                              @"weiba_id":self.community.weiba_idSB
                              };
        
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
        
        [self dataSourceWithJasonDic:responseDic];
        [self.tableView.header endRefreshing];
    } errorBlock:^(NSError *error) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        [self.tableView.header endRefreshing];

    }];
    
 
    
    
}


#pragma mark- 上拉加载方法（请求数据，结束footer） -

 -(void)loadMoreData{
 
     //http://api.gongniucaijing.com/Weiba/listpost ? weiba_id=3&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&number=15
     NSString *urlStr = @"http://api.gongniucaijing.com/Weiba/listpost";
     
     [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
         HotPost *hotpost = [[HotPost alloc]init];
         hotpost = [self.hotPostArray lastObject];
         NSString *time = [@"0." stringByAppendingString:hotpost.time];
         NSDictionary *dic = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                               @"number":@"15",
                               @"weiba_id":self.community.weiba_idSB,
                               @"post_time":time
                               };
         
         return dic;
     } successBlock:^(NSDictionary *responseDic) {
         
         [self dataSourceWithJasonDic:responseDic];

         [self.tableView.footer endRefreshing];
     } errorBlock:^(NSError *error) {
         
         UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
         
         [alertView show];
         [self.tableView.footer endRefreshing];
         
     }];
     
 
 
 }
 


#pragma mark- 共用方法：数据源赋值，reloadData -
- (void)dataSourceWithJasonDic:(NSDictionary *)dic{
    if (dic) {
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
//        NSDictionary *postDic = [dataDic objectForKey:@"post"];
        NSArray *listsArray = [dataDic objectForKey:@"lists"];
        for (NSDictionary *dic in listsArray) {
            
            HotPost *hotPost = [[HotPost alloc]init];
            //            用KVC给模型赋值
            [hotPost setValuesForKeysWithDictionary:dic];

            [self.hotPostArray addObject:hotPost];
            
            
            
        }
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        //        刷新视图
        [self.tableView reloadData];
        
        
        
    }
    
}

//#pragma mark- 重写hotPostArray Get方法 -
//-(NSMutableArray *)hotPostArray{
//    if (_hotPostArray == nil) {
//        _hotPostArray = [NSMutableArray array];
//        
//    }
//    
//    return _hotPostArray;
//}



#pragma mark- 协议方法：分行 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.hotPostArray.count;
}

#pragma mark- 分区 -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

#pragma mark- 协议方法cell复用 -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HotPostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hotPostCell" forIndexPath:indexPath];
    //    在数据源里面取模型
    HotPost *hotPost = [self.hotPostArray objectAtIndex:indexPath.row];
    //    把它赋给cell的模型的属性，以便走进cell的set方法给cell上的label等属性赋值
    cell.hotPost = hotPost;
    
    if (hotPost.post_avatarImage == nil) {
        

        
        [cell.post_avatarImageView sd_setImageWithURL:[NSURL URLWithString:hotPost.post_avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            hotPost.post_avatarImage = cell.post_avatarImageView.image;
        }];
        
    }
    
    
    if (hotPost.post_logoImage == nil) {

        [cell.post_logoImageView sd_setImageWithURL:[NSURL URLWithString:hotPost.post_logo] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            hotPost.post_logoImage = cell.post_logoImageView.image;
            
            if (!hotPost.post_logoImage) {

                cell.post_logoImageView.frame=CGRectMake(cell.post_logoImageView.frame.origin.x, cell.post_logoImageView.frame.origin.y, 10, 0);
                
            }else {
     
                
                NSString * contentStr = [hotPost.contentSB stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
                NSString * content = [contentStr stringByReplacingOccurrencesOfString:@"<br/>" withString:@"\n"];
                
                
                CGFloat contentLabelHeight = [MyHandle stringHeight:content fontSize:12 width:self.view.bounds.size.width-20];
                
                CGFloat width1 = (120*image.size.width)/image.size.height;
                cell.post_logoImageView.frame = CGRectMake(cell.post_logoImageView.frame.origin.x, contentLabelHeight+110, width1, 120);
                

                
            }
            
        }];
        
    }
    
    
    cell.post_avatarImageView.image = hotPost.post_avatarImage;
    cell.post_logoImageView.image = hotPost.post_logoImage;
    
    
    
    if (!hotPost.post_logoImage) {
        //        self.post_logoImageView = nil;
        cell.post_logoImageView.frame=CGRectMake(cell.post_logoImageView.frame.origin.x, cell.post_logoImageView.frame.origin.y, 10, 0);
        
    }else {

        
        UIImage *image=hotPost.post_logoImage;
        
        NSString * contentStr = [hotPost.contentSB stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
        NSString * content = [contentStr stringByReplacingOccurrencesOfString:@"<br/>" withString:@"\n"];
        
        
        CGFloat contentLabelHeight = [MyHandle stringHeight:content fontSize:12 width:self.view.bounds.size.width-20];
        
        CGFloat width1 = (120*image.size.width)/image.size.height;
        
        cell.post_logoImageView.frame = CGRectMake(cell.post_logoImageView.frame.origin.x, contentLabelHeight+110, width1, 120);
        
    }
    
    return cell;
    
}

#pragma mark- cell被选中的方法 -
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CommentViewController *commentVC = [[CommentViewController alloc]initWithHeader:YES footer:YES];
    HotPost *hotPost = [self.hotPostArray objectAtIndex:indexPath.row];
    commentVC.hotPost = hotPost;
    [self.navigationController pushViewController:commentVC animated:YES];
    
    
    
    
    
}







#pragma mark- 自定义cell高度 -
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HotPost *hotPost = [self.hotPostArray objectAtIndex:indexPath.row];
    //    HotPostTableViewCell *cell = [[HotPostTableViewCell alloc]init];
    
    [MyHandle new];
    //    做出判断，如果模型中有image的url，就证明有imageView
    CGFloat height1 = 0;
    if ([hotPost.post_logo length]>2) {
        height1 = 140;
        
    }else if ([hotPost.post_logo length]<2){
        
        height1 = 0;
    }
    
    CGFloat contentHeight2 = [MyHandle stringHeight:hotPost.contentSB fontSize:12 width:self.view.bounds.size.width-20];
    

    
    return 15+40+15+contentHeight2+55+height1;
    
    
}





/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
